<?php

namespace App\Http\Controllers\Admin;
use App\DTOS\Admin\ServerGroupDTO;
use App\Http\Controllers\Controller;
use App\Models\Game\GamePackage;
use App\Services\Game\ConfigGroupService;
use App\Services\Game\ServerGroupService;
use App\Utils\ResponseUtil;
// 配置分组列表
class ConfigGroupController extends Controller
{
    private ConfigGroupService $ConfigGroupService;

    /**
     * ServerGroupController constructor.
     * @param ConfigGroupService $ConfigGroupService
     */
    public function __construct(ConfigGroupService $ConfigGroupService)
    {
        $this->ConfigGroupService = $ConfigGroupService;
    }

    public function paginate()
    {
        $paginate = $this->ConfigGroupService->paginate(new ServerGroupDTO(request()->all()));

        $res = [];
        $res['code'] = 0;
        $res['msg'] = 'success';
        $res['data'] = [];

        // 确保 items 是集合
        $items = collect($paginate->items());

        // 获取 type 列表
        $types = $items->pluck('type')->unique();

        // 查询 GamePackage 表
        $gamePackages = GamePackage::whereIn('configtype', $types)->get();

        // 组装结果
        foreach ($items as $item) {
            // 过滤与当前 item 类型匹配的 GamePackage
            $matchingPackages = $gamePackages->where('configtype', $item->type);

            // 组装 channel_info
            $channelPackages = $matchingPackages->map(function ($package) {
                return $package->channelcg . ':' . $package->package_no;
            });

            // 将 channelcg:package_no 用逗号隔开
            $item->channel_info = $channelPackages->implode(',');

            // 将处理后的项添加到结果中
            $res['data'][] = $item;
        }

        $res['count'] = $paginate->total();
        return ResponseUtil::json($res);
    }

    public function hvpaginate()
    {
        $paginate = $this->ConfigGroupService->paginate(new ServerGroupDTO(request()->all()));

        $res = [];
        $res['code'] = 0;
        $res['msg'] = 'success';
        $res['data'] = $paginate->items();
        $res['count'] = $paginate->total();
        return ResponseUtil::json($res);
    }

    public function add()
    {
        $data = request()->all();
        $this->ConfigGroupService->add($data);
        return ResponseUtil::success();
    }
    public function edit($id)
    {
        $data = request()->all();
        $this->ConfigGroupService->edit($id,$data);
        return ResponseUtil::success($data);
    }
    public function detail($id)
    {
        $data = $this->ConfigGroupService->detail($id);
        return ResponseUtil::success($data);
    }
    public function delete($id)
    {
        $this->ConfigGroupService->delete($id);
        return ResponseUtil::success();
    }
}
